const { readFileSync } = require('fs')
const { resolve } = require('path')
const os = require('os')

const INNER_MARK = '<!-- inner -->'

class MdToHtmlPlugin {
  constructor(options) {
    this.template = options.template
    this.filename = options.filename ?? 'md.html'
  }

  apply(compiler) {
    compiler.hooks.emit.tap('md-to-html-plugin', (compilation) => {
      const _assets = compilation.assets
      const _mdContent = readFileSync(this.template, 'utf-8')
      const _templateHTML = readFileSync(resolve(__dirname, 'template.html'), 'utf-8')
      const _mdContentArr = _mdContent.split(os.EOL)
      const _htmlStr = compileHTML(_mdContentArr)
      const _finalHTML = _templateHTML.replace(INNER_MARK, _htmlStr)
      
      _assets[this.filename] = {
        source() {
          return _finalHTML
        },
        size() {
          return _finalHTML.length
        }
      }
    })
  }
}

function compileHTML(contentArr) {
  return contentArr.join('.')
}

module.exports = MdToHtmlPlugin;